<?php namespace App\Controllers;

use \App\App;

class Download extends App {
    private $filePath = BASE_PATH . '/assets/uploads/';
    private $story;

    public function __construct() {
        parent::__construct();
    }

    public function index() {
        $id = $this->request->post('id');
        $type = $this->request->post('type');
        if (!$id) {
            $this->showJson(['error' => '未找到要下载的小说。']);
        }

        $storyModel = new \App\Models\Story();
        $this->story = $storyModel->find($id);
        $this->filePath .="_". substr($id, 0, 1);
        
        if (!$this->story) {
            $this->showJson(['error' => '未找到小说内容']);
        }

        if (!is_dir($this->filePath)) {
            mkdirs($this->filePath);
        }
        
        $name=$this->create($id).($type == "epub"?".epub":".txt");
        
        if (! file_exists ($this->filePath.'/'.$name)) {
            $this->showJson("文件不存在或未生成，请联系管理员","error");
        } else {
           $this->showJson(["path"=>"_".substr($id, 0, 1),'name'=>urlencode($name)]);
        } 
    }

    public function get($path,$name) {
        $file =$this->filePath .$path.'/'.urldecode($name);
        $f = fopen ( $file, "rb" );
        header ( "Content-type: application/octet-stream; charset=utf-8" ); 
        header("Content-Transfer-Encoding: binary");
        header('Content-Description: File Transfer');    
        header ( "Accept-Ranges: bytes" );  
        header ( "Accept-Length: " . filesize ( $file) );          
        header ( "Content-Disposition: attachment; filename=" . urldecode($name) ); 
        while(!feof($f)) {
            echo fread($f, 10240);
        }
        fclose ( $f ); 
        $statModel=new \App\Models\Stat();
        $stat=$statModel->where('date',date("Y-m-d"))->first();
        if ($stat) {
            $stat['download']++;
        } else {
            $stat=[
                'date'=>date("Y-m-d"),
                'visit'=>1,
                'story'=>0,
                'download'=>1
            ];
        }
        $statModel->save($stat);
        exit (); 
    }

    public function create($id) {
        $epub = new \App\Libraries\Epub();
        $fileName =  "《".$this->story['title'] . '》';
        $file = fopen($this->filePath . '/' . $id . '_id.txt', 'w+');
        $sort = fgets($file);
        $this->db->where('id>', $sort ?: 0);
        $chapters = $this->db->table($id)->select("id,title,UNCOMPRESS(content) as content")->get()->result();  
        if ($this->db->error)       {
            $this->showJson($this->db->error,"error");
        }
        $textContent="";
        if ($chapters) {
            //EPUB
            $epub->temp_folder = $this->filePath;
            $epub->epub_file = $this->filePath . '/' .$fileName.".epub";
            $epub->title = $this->story['title'];
            $epub->creator=$this->story['author'];
            $epub->publisher="DMNovel";
            $epub->css = ".content {text-indent: 2em;}";
            $epub->AddImage($this->story['cover'] ? 'assets/images/covers/' . $this->story['cover'] : 'assets/images/covers/default.jpg', 'image/jpeg', true);
            foreach ($chapters as $chapter) {
                $textContent.= $chapter['title']."\n\n"
                .$chapter['content']."\n\n";
                $content = '<h2>' . $chapter['title'] . '</h2><br />'
                    . '<div class="content"><p>'
                    . preg_replace("/\n/", "</p><p>", $chapter['content'])
                    . "</p></div>";
                $epub->AddPage($content, false, $chapter['title']);
            }
                       
            $epub->CreateEPUB();

            if ($epub->error) {
                $this->showJson( $epub->error,"error");
            }
            //TXT
            $txt=fopen($this->filePath . '/' . $fileName . '.txt', 'a+');
            fwrite($txt,$textContent);
            fclose($txt);
            fputs($file, $chapters[count($chapters) - 1]['id']);            
        }
        fclose($file);    
        return $fileName;
    }
}